/*
Filename: UCAdminRegist.java
Precondition: administrator enter a invalid administrator name and password
Post-condition: administrator registers in the system
Main success Scenario:
1. Administrator selects to register
2. Administrator enters name and password
3. Administrator clicks ‘register’ button
4. System checks administrator name and password are valid
5. System checks with database that administrator is unique.
6. System registers administrator and password with database
7. System registers the administrator information.
8. System displays message “Registration Successful
9. System updates the main UI.
2a. Extensions: System detects invalid register:
1. System display “invalid administrator register “message

 */

package ucm;

/**
 *
 * @author Mark
 */
import model.UsersModel;
import model.DatabaseModel;
import view.adminRegister;

import javax.swing.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;

public class UCAdminRegist implements UCController {

    private UsersModel user;

    public UCAdminRegist() {
        user = new UsersModel("", "", "", "", "");
    }

    public UCAdminRegist(UsersModel user) {
        // System retrieves username and password
        this.user = user;
    }

    public UCAdminRegist(adminRegister adminRegister) {
        // System retrieves username and password
        this.user = adminRegister.getUserModel();
    }

    // STEP 1 - User Selects Register
    public boolean run() {
        boolean registeredSuccessful = false;
        // STEP 2 - System retrieves username and password
        // This step is integrated into the constructor or
        // may be specified by using run(UserModel)
        // STEP 3 - System checks username and password are valid (greater than 4 characters)
        if (validDetails()) {
            //Step 4 - System checks with database that username is unique
            if (uniqueUser()){
                //Step 5 - System registers username and password with database
                if (registerUser()) {
                    // STEP 6 - System displays 'Registered Successfully' message
                    JOptionPane.showMessageDialog(new JFrame(),
                            "Registered Successfully!",
                            "Success",
                            JOptionPane.INFORMATION_MESSAGE);
                      new ucm.UCDisplayAdminLogin();
                    registeredSuccessful = true;
                } else {
                    JOptionPane.showMessageDialog(new JFrame(),
                            "Registration failed for unknown reason",
                            "Error Message",
                            JOptionPane.ERROR_MESSAGE);
                }
            } else {
                //Step 4a - System displays 'username not unique' message
                JOptionPane.showMessageDialog(new JFrame(),
                        "Username already exists, please choose another",
                        "Error Message",
                        JOptionPane.ERROR_MESSAGE);
            }
        } else {
            //Step 3a - System displays 'invalid user details' message
            JOptionPane.showMessageDialog(new JFrame(),
                    "Username or password invalid (must be between 5 and 10 characters)",
                    "Error Message",
                    JOptionPane.ERROR_MESSAGE);
        }
        return registeredSuccessful;
    }

    // STEP 1 - User Selects Register
    public void run(UsersModel user) {
        // STEP 2 - System retrieves username and password
        this.user = user;
        // STEP 3 onwards
        run();
    }

    private boolean validDetails() {
        // Check the length of the username and password
        return (user.getUsername().length() >= 4) &&
                (user.getUsername().length() <= 16) &&
                (user.getPassword().length() >= 4) &&
                (user.getPassword().length() <= 16);
    }

    private boolean uniqueUser() {
        boolean unique = false;
        String username = user.getUsername();

        Connection con = DatabaseModel.getInstance().getConnection();

        try {
            Statement stmt = con.createStatement(ResultSet.CONCUR_UPDATABLE,
                    ResultSet.CONCUR_UPDATABLE);

            ResultSet res = stmt.executeQuery("SELECT * FROM admins WHERE " +
                    "aname = '" + username + "'");

            unique = !(res.first() && username.equals(res.getString("uname")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return unique;

    }

    private boolean registerUser(){
        boolean register = false;
        String username = user.getUsername();
        String password = user.getPassword();
        String phone = user.getPhone();
        String email = user.getemail();
        String purview = user.getpurview();
        if(purview.equals("admin")){
        DatabaseModel dbModel = DatabaseModel.getInstance();

        Connection con = dbModel.getConnection();
        try {
            Statement stmt = con.createStatement(ResultSet.CONCUR_UPDATABLE,
                    ResultSet.CONCUR_UPDATABLE);

            stmt.executeUpdate("INSERT INTO admins(`ANAME`, `APASSWORD`, `APHONE`, `AEMAIL`) values('" + username + "', '" + password + "', " + phone +", '" + email +"')");
            //database.
            register = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        }
        return register;
    }
}
